package com.example.floatingclockdemo

import android.app.ActivityManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsControllerCompat
import com.example.floatingclockdemo.ui.theme.FloatingClockDemoTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 设置状态栏为黑色字体
        WindowCompat.setDecorFitsSystemWindows(window, true)
        WindowInsetsControllerCompat(window, window.decorView).isAppearanceLightStatusBars = true

        setContent {
            FloatingClockDemoTheme {
                ClockControlUI()
            }
        }
    }
}

// 业务逻辑 + UI 组合层
@Composable
fun ClockControlUI() {
    val context = LocalContext.current
    var isRunning by remember {
        mutableStateOf(isServiceRunning(context, ClockService::class.java))
    }

    // 注册广播接收器：监听服务关闭
    DisposableEffect(Unit) {
        val receiver = object : BroadcastReceiver() {
            override fun onReceive(c: Context?, intent: Intent?) {
                if (intent?.action == BROADCAST_CLOCK_SERVICE_STOP) {
                    isRunning = false
                }
            }
        }

        val intentFilter = IntentFilter(BROADCAST_CLOCK_SERVICE_STOP)
        val flag = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
            Context.RECEIVER_NOT_EXPORTED else 0

        context.registerReceiver(receiver, intentFilter, flag)

        onDispose {
            context.unregisterReceiver(receiver)
        }
    }

    ClockControlButton(isRunning = isRunning) {
        if (Settings.canDrawOverlays(context)) {
            if (!isRunning) {
                context.startService(Intent(context, ClockService::class.java))
                val homeIntent = Intent(Intent.ACTION_MAIN).apply {
                    addCategory(Intent.CATEGORY_HOME)
                    flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                context.startActivity(homeIntent)
                isRunning = true
            }
        } else {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                "package:${context.packageName}".toUri()
            )
            context.startActivity(intent)
        }
    }
}

// 可复用 + 可预览的 UI 层
@Composable
fun ClockControlButton(
    isRunning: Boolean,
    onClick: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color(0xFFF7F7F7)),
        contentAlignment = Alignment.Center
    ) {
        Button(
            onClick = onClick,
            enabled = !isRunning,
            colors = ButtonDefaults.buttonColors(
                containerColor = Color(0xFF4CAF50),
                contentColor = Color.White,
                disabledContainerColor = Color(0x994CAF50),
                disabledContentColor = Color.White
            ),
            shape = RoundedCornerShape(24.dp),
            modifier = Modifier.padding(horizontal = 32.dp, vertical = 16.dp)
        ) {
            Text(text = if (isRunning) "悬浮时钟已启动" else "开启悬浮时钟")
        }
    }
}

// 可预览的样式函数
@Preview(showBackground = true)
@Composable
fun ClockControlButtonPreview() {
    FloatingClockDemoTheme {
        ClockControlButton(isRunning = false) {}
    }
}

// 工具函数：判断服务是否在运行
fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
    val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    @Suppress("DEPRECATION")
    return manager.getRunningServices(Int.MAX_VALUE)
        .any { it.service.className == serviceClass.name }
}